package com.yuncheng.spcyApi.flowService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.FlowJobBlsxService;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.SpBzFlowConstant;
import com.yuncheng.spcyApi.constant.flow.YlqxFlowConstant;
import com.yuncheng.spcyApi.constant.flow.YpscFlowConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcySqsxBaiscService;
import com.yuncheng.spcyApi.service.ISpcySqsxJobService;
import com.yuncheng.spcyApi.service.ISysUserFgldService;
import com.yuncheng.spcyApi.service.impl.YcSysUserServiceImpl;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;

import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.spcyApi.vo.flow.YpscFlowVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.util.*;

@Component(value = "reissueFlowService")
public class SpBzFlowService extends FlowService {
    private static final Logger log = LoggerFactory.getLogger(SpBzFlowService.class);

    @Resource
    @Lazy
    private SpBzFlowConstant flowConstant;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISysUserFgldService sysUserFgldService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private YcSysUserServiceImpl ycSysUserService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private FlowJobBlsxService flowJobBlsxService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    public Result handleFlow(YpscFlowVo ypscFlowVo, SpcySqsxJob nowJob, String jobId, String sqsxid, String submitType, String opinion){
        // 当前流程任务
        if (StringUtils.isNotBlank(jobId)) {
            nowJob = spcySqsxJobService.getById(jobId);
        }

        if (nowJob == null){
            return Result.error("当前流程任务不存在，请重试");
        }

        if (StringUtils.isBlank(sqsxid)){
            sqsxid = nowJob.getFpid();
        }

        // 提交按钮
        if (submitType.equals(SpBzFlowConstant.SUBMIT_TYPE_SUBMIT)) {
            if (nowJob == null) {
                return Result.error("当前流程任务不存在");
            }
        }
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("登录已失效，请重新登录");
        }

        if (StringUtils.isNotBlank(nowJob.getFhjmc()) && nowJob.getFhjmc().equals(SpBzFlowConstant.HJMC_SP)){
            // 流程环节处理
            Result httpResult = handleNodeName(ypscFlowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }else if (submitType.equals(SpBzFlowConstant.SUBMIT_TYPE_SUBMIT)){
                this.stopSpcyFlowNodeEnd(sqsxid); // 主流程-暂停时间

                SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
                if (sqsx != null){
                    sqsx.setFspbzlczt(SpBzFlowConstant.HJMC_LCJS); // 流程结束
                    spcySqsxBaiscService.updateById(sqsx);
                }

                /**
                 * 给主办人发送办结短信
                 */
                String msg = "";
                String zbrHzKsfzr = busService.getZbrHzKsfzr(sqsx);// 获取主办人
                String nextNodeSmsContent = busService.getNextNodeSmsContent(sqsx, null, null); // 获取短信内容

                msg += nextNodeSmsContent;
                msg += flowConstant.getFlowName() + "->处于[ " + SpBzFlowConstant.HJMC_SP + " ]环节已经办结了。办理意见为[ ";
                msg += opinion;
                msg += " ]";

                busService.sendSmsToNodeDbr(zbrHzKsfzr, null,msg);

            }

        }else {

            // 流程环节处理
            Result httpResult = handleNodeName(ypscFlowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()) {
                return httpResult;
            }
        }

        return Result.ok("操作成功");
    }

    public Result handleNodeName(YpscFlowVo ypscFlowVo,String submitType, SpcySqsxJob job, String sqsxId, String opinion){
        HashMap<String, Object> map = ypscFlowVo.getMap();
        String dbrid = ypscFlowVo.getDbrid();// 下环节待办人
        String smgflag = ypscFlowVo.getSmgflag(); // 短信发送标志
        boolean isSubmit = true; // 是否提交流程
        Result res = null;

        // 保存按钮
        if (submitType.equals(SpBzFlowConstant.SUBMIT_TYPE_SAVE)){

        }

        // 提交按钮
        if (submitType.equals(SpBzFlowConstant.SUBMIT_TYPE_SUBMIT)){

            // 流程任务id
            String jobId = "";
            if (job != null){
                jobId = job.getId();
            }

            // 提交流程任务,待办人是否为空，指定待办人
            if (isSubmit) {
                if (StringUtils.isBlank(dbrid)) {
                    // 提交-流程任务
                    res = this.passJob(sqsxId, jobId, opinion, "", "");
                } else {
                    // 提交-流程任务
                    res = this.passJob(sqsxId, jobId, opinion, "", dbrid);
                }
            }
            if (!res.isSuccess()){
                return res;
            }else {
                SpcySqsxJob nowJob = (SpcySqsxJob)res.getResult();
                // 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                if (nowJob != null && !jobId.equals(nowJob.getId()) && StringUtils.isNotBlank(smgflag) && smgflag.equals("是")){
                    busService.sendSmsToPassJob(nowJob);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 撤回流程
     * @param jobid
     * @param opinion
     * @return
     */
    public Result returnSpBzFlow(String jobid,String opinion){
        if (StringUtils.isBlank(jobid)){
            return Result.error("参数丢失，请联系管理员");
        }
        SpcySqsxJob nowJob = spcySqsxJobService.getById(jobid);
        if (nowJob == null){
            return Result.error("当前流程任务不存在，请刷新重试");
        }
        if (StringUtils.isNotBlank(nowJob.getFblzt()) && nowJob.getFblzt().equals(SpcyConstant.BLZT_YB)){
            return Result.error("当前环节【"+nowJob.getFhjmc()+"】已经办理，无法撤回");
        }

        String nowNode = nowJob.getFhjmc(); // 当前环节
        String previousName = flowConstant.getPreviousName(nowNode); // 上环节名称

        StringBuffer logNr = new StringBuffer("撤回流程：\n");

        // 判断是否为第一个环节
        if (nowNode.equals(previousName)){
            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(nowJob.getFpid());
            if (sqsx != null){
                sqsx.setFspbzlczt("");
                spcySqsxBaiscService.updateById(sqsx);
            }

            // 判断是否存在，书面审查意见环节，按发送时间倒序，存在多个取当前第一个
            List<SpcySqsxJob> smscJobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                    .eq(SpcySqsxJob::getFpid, nowJob.getFpid())
                    .eq(SpcySqsxJob::getFhjmc, SpBzFlowConstant.HJMC_SMSCYJ)
                    .orderByDesc(SpcySqsxJob::getFfssj));
            if (CollectionUtils.isNotEmpty(smscJobList)){
                spcySqsxJobService.removeById(smscJobList.get(0).getId());
            }

            spcySqsxJobService.removeById(jobid);
            logNr.append("环节名称").append("[").append(nowNode).append("]");

        } else if (nowNode.equals(SpBzFlowConstant.HJMC_SP)){
            // 上环节
            String fsyhjid = nowJob.getFsyhjid();
            if (StringUtils.isNotBlank(fsyhjid)) {
                SpcySqsxJob preJob = spcySqsxJobService.getById(fsyhjid);
                if (preJob != null) {
                    preJob.setFblzt(SpcyConstant.BLZT_TH);
                    preJob.setFbllx(SpcyConstant.BLLX_DB);
                    preJob.setFblyj(opinion);
                    preJob.setFthyj(opinion);
                    boolean save = spcySqsxJobService.updateById(preJob);

                    if (save) {
                        // 发送退回短信
                        String nextNodeSmsContent = busService.getNextNodeSmsContent(preJob, null);
                        busService.sendNextNodeSmsContent(preJob, nextNodeSmsContent);
                    }
                }
            }

            spcySqsxJobService.removeById(jobid);
            logNr.append("环节名称").append("[").append(nowNode).append("]");
        }

        if (StringUtils.isNotBlank(opinion)){
            logNr.append("\n").append("撤回意见").append("[").append(opinion).append("]。");

            logNr.append("\n").append(LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(nowJob)));
        }
        spcyLogService.addLogs(nowNode,logNr.toString(),nowJob.getFpid(),SpcyConstant.LOGS_SYS_TYPE_TH,SpcyConstant.LOGS_SYS_TYPE_TH);

        return Result.ok("撤回成功");
    }

    /**
     * 补正流程-暂停主流程环节-开始
     */
    public Result stopSpcyFlowNodeStart(String sqsxid){

        // 查询审评查验流程-当前待办环节
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .like(SpcySqsxJob::getFlcmc, YpscFlowConstant.LCMC_LIKE_SPCYLC)
                .orderByAsc(SpcySqsxJob::getFfssj));

        if (CollectionUtils.isEmpty(jobList)){
            return Result.ok("操作成功");
        }

        SpcySqsxJob stopJob = null;

        /**
         * 查找-处于主流程-发起补正流程的环节，将该环节暂停。
         */
        if (jobList.size() == 1){

            stopJob = jobList.get(0);

        }else if (jobList.size() > 1){
            for (SpcySqsxJob nowJob : jobList){

                if (StringUtils.isBlank(nowJob.getFhjmc())){
                    continue;
                }

                if (!nowJob.getFhjmc().equals(YlqxFlowConstant.HJMC_FAZZ)){
                    continue;
                }

                stopJob = nowJob;
            }
        }

        if (stopJob == null){
            return Result.ok("操作成功");
        }

        if (stopJob.getFztkssj() == null) {
            stopJob.setFztkssj(new Date());
            spcySqsxJobService.updateById(stopJob);
        }

        return Result.ok("暂停流程成功");
    }

    /**
     * 补正流程-暂停主流程环节-结束
     */
    public Result stopSpcyFlowNodeEnd(String sqsxid){
        // 查询审评查验流程-当前待办环节
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .like(SpcySqsxJob::getFlcmc, YpscFlowConstant.LCMC_LIKE_SPCYLC)
                .orderByAsc(SpcySqsxJob::getFfssj));

        if (CollectionUtils.isEmpty(jobList)){
            return Result.ok("操作成功");
        }

        SpcySqsxJob stopJob = null;

        /**
         * 查找-处于主流程-发起补正流程的环节，将该环节取消暂停。
         */
        if (jobList.size() == 1){

            stopJob = jobList.get(0);

        }else if (jobList.size() > 1){
            for (SpcySqsxJob nowJob : jobList){

                if (StringUtils.isBlank(nowJob.getFhjmc())){
                    continue;
                }

                if (!nowJob.getFhjmc().equals(YlqxFlowConstant.HJMC_FAZZ)){
                    continue;
                }

                stopJob = nowJob;

            }
        }

        if (stopJob == null){
            return Result.ok("操作成功");
        }
        if (stopJob.getFztkssj() == null){
            return Result.ok("操作成功");
        }

        Date fztkssj = stopJob.getFztkssj(); // 暂停开始时间
        Date fztjssj = new Date(); // 暂停结束时间
        String jssygzr = flowJobBlsxService.jssygzr(fztkssj, fztjssj);
        stopJob.setFztsyts(jssygzr); // 计算暂停使用天数
        stopJob.setFztjssj(fztjssj);
        spcySqsxJobService.updateById(stopJob);

        return Result.ok("取消暂停流程成功");
    }

    /**
     * 终止流程
     */
    public Result endFlowJob(String jobid){
        if (StringUtils.isBlank(jobid)){
            return Result.error("流程参数为空");
        }
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        String sqsxid = job.getFpid();
        if (job == null){
            return Result.error("当前流程记录不存在，请刷新重试");
        }
        if (StringUtils.isNotBlank(job.getFblzt()) && job.getFblzt().equals(SpcyConstant.BLZT_YB)){
            return Result.error("当前流程任务已经结束！");
        }
        job.setFblsj(new Date());
        job.setFblyj("终止办结。");
        job.setFblzt(SpcyConstant.BLZT_YB); // 已办
        job.setFbllx(SpcyConstant.BLLX_BL);
        job.setFsyts(flowJobBlsxService.jssygzr(job.getFfssj(), job.getFblsj())); // 使用天数
        job.setFsfcs(flowJobBlsxService.isDateBetweenSfcs(job.getFsyts(), job.getFcnts())); // 办理是否超时
        boolean flag = spcySqsxJobService.updateById(job);
        if (flag) {
            this.stopSpcyFlowNodeEnd(sqsxid);

            String log = "终止专家流程-环节名称-[" + job.getFhjmc() + "]。";
            spcyLogService.addLogs(job.getFhjmc(), log, job.getFpid(), SpcyConstant.LOGS_SYS_TYPE_TJ, SpcyConstant.LOGS_SYS_TYPE_TJ);

            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx != null){
                sqsx.setFspbzlczt(SpBzFlowConstant.HJMC_LCJS);
                spcySqsxBaiscService.updateById(sqsx);
            }
        }

        return Result.ok("终止成功");
    }

    /**
     *  获取补正流程最后一个环节的办理意见
     */
    public String getLastNodeBlyj(String sqsxid){
        String msg = "";

        if (StringUtils.isBlank(sqsxid)){
            return msg;
        }

        // 获取 补正流程 - 分管审批 - 已办 - 最新的办理意见
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFhjmc, SpBzFlowConstant.HJMC_SP)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .eq(SpcySqsxJob::getFlcmc, SpBzFlowConstant.FLOW_NAME)
                .orderByDesc(SpcySqsxJob::getFfssj));

        if (CollectionUtil.isNotEmpty(jobList)){
            msg = Optional.ofNullable(jobList.get(0)).map(SpcySqsxJob::getFblyj).filter(StringUtils::isNotBlank).orElse("");
        }

        return msg;
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid){
        Map map = new HashMap();

        // 当前流转记录
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            log.error("当前流程任务id为【{}】的流转记录不存在",jobid);
            return map;
        }
        String sqsxid = job.getFpid();
        if (org.apache.commons.lang3.StringUtils.isBlank(sqsxid)){
            log.error("当前流程任务id为【{}】的流转记录中的申请事项id为空",jobid);
            return map;
        }

        // 申请事项基本信息
        SpcySqsxBasic sqsxBasic = spcySqsxBaiscService.getById(sqsxid);

       /* // 企业相关信息
        SpcyQyJbxx qyJbxx = null;
        if (sqsxBasic != null && org.apache.commons.lang3.StringUtils.isNotBlank(sqsxBasic.getFqyid())){
            qyJbxx = busService.getQyjbxx(sqsxBasic.getFqyid());
        }
        map.put("qy",qyJbxx);*/

        // 流程任务流传记录
        List<SpcySqsxJob> jobList = this.getJobListBySqsxId(sqsxid);

        // 申请事项相关文件记录
        List<SpcySqsxWjjl> wjjlList = busService.getWjjlListBySqsxId(sqsxid);

        // 申请事项的检查项目
//        List<SpcySqsxJcxm> jcxmList = getJcxmQxListBySqsxId(sqsxBasic);

        // 申请事项的选派记录-查验
        List<SpcySqsxXpjl> cyxpjlList = busService.getTyXpXpjlList(sqsxid,SpcyConstant.FLOW_TYPE_CY);

        // 申请事项的选派记录-审评
        List<SpcySqsxXpjl> spxpjlList = busService.getTyXpXpjlList(sqsxid,SpcyConstant.FLOW_TYPE_SP);

        // 获取下环节待办人
        String nextNode = flowConstant.getNextNodeName(job.getFhjmc());
        Map nextDbr = this.getNodeDbr(sqsxid, nextNode,"");
        List<AgentVo> dbrListByMap = busService.getDbrListByMap(nextDbr);

        map.put("sqsx",sqsxBasic); // 申请事项基本信息
        map.put("job",job); // 当前流转记录
        map.put("jobHistoryList",jobList); // 流程任务流传记录
        map.put("wjjlList",wjjlList); // 申请事项-相关文件
        map.put("cyxpjlList",cyxpjlList); // 申请事项-选派记录-查验
        map.put("spxpjlList",spxpjlList); // 申请事项-选派记录-审评
        map.put("nextNodeDbrList",dbrListByMap); // 下环节待办人list
        map.put("nextNode",nextNode);

        return map;
    }

    /**
     * 获取申请事项-流转记录
     */
    public List<SpcySqsxJob> getJobListBySqsxId(String sqsxid){
        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SpcySqsxJob::getFlcmc, flowConstant.getFlowName());
        queryWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);

        return jobList;
    }

    // 初始化-书面审查意见-环节
    public Result initSmscyjJob(String sqsxId, String smscyj, CurrentUserVo currentUser){
        // 验证申请事项-补正流程是否已经完成
        Result result = this.veriftBzJobState(sqsxId);
        if (!result.isSuccess()){
            return Result.error(result.getMessage());
        }

        SpcySqsxJob smscyjJob = new SpcySqsxJob();
        smscyjJob.setId(GetUuIdUtils.ReplaceUuId());
        smscyjJob.setFblzt(SpcyConstant.BLZT_YB);
        smscyjJob.setFblfs(flowConstant.getBlfs(SpBzFlowConstant.HJMC_SMSCYJ));
        smscyjJob.setFblyj(smscyj);
        smscyjJob.setFfssj(DateUtil.offsetMinute(new Date(),-1));
        smscyjJob.setFblsj(DateUtil.offsetMinute(new Date(),-1));
        smscyjJob.setFdbrid(currentUser.getId());
        smscyjJob.setFdbr(currentUser.getName());
        smscyjJob.setFblr(currentUser.getName());
        smscyjJob.setFhjmc(SpBzFlowConstant.HJMC_SMSCYJ);
        smscyjJob.setFpid(sqsxId);
        smscyjJob.setFlcmc(flowConstant.getFlowName());
        boolean flag = spcySqsxJobService.save(smscyjJob);
        if (flag) {
            String lognr = "初始化补正流程：";
            lognr += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(smscyjJob));
            spcyLogService.addLogs(SpBzFlowConstant.HJMC_SMSCYJ, lognr, sqsxId, SpcyConstant.LOGS_SYS_TYPE_TJ, SpcyConstant.LOGS_SYS_TYPE_TJ);
        }

        String nodeName = flowConstant.getFirstNode();
        return this.createNextJob(flowConstant,sqsxId,null,currentUser,nodeName,"");
    }

    // 验证申请事项-补正流程是否已经完成
    public Result veriftBzJobState(String sqsxid){
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
                .and(
                        f -> f.eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_DB)
                                .or()
                                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_TH)
                ));
        if (CollectionUtils.isNotEmpty(jobList)){
            return Result.error("请先完成当前的补正流程，再进行发起新的补正流程！");
        }

        return Result.ok("操作成功");
    }

    //初始化任务
    public Result initJob(String sqsxId, CurrentUserVo currentUser){
        // 验证申请事项-补正流程是否已经完成
        Result result = this.veriftBzJobState(sqsxId);
        if (!result.isSuccess()){
            return Result.error(result.getMessage());
        }
        String nodeName = flowConstant.getFirstNode();
        //需要校验是否已经初始化过
        /*List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxId)
                .eq(SpcySqsxJob::getFhjmc, nodeName)
                .eq(SpcySqsxJob::getFlcmc, flowConstant.getFlowName())
        );*/
//        if(list.size()>0){
            /*List<String> ids = list.stream().map(SpcySqsxJob::getId).collect(Collectors.toList());
            spcySqsxJobService.removeBatchByIds(ids);*/
//            return Result.error("发起失败，已经发起过流程了");
//        }
//        return this.initJob(flowConstant,sqsxId,currentUser);
        return this.createNextJob(flowConstant,sqsxId,null,currentUser,nodeName,"");
    }

    /**
     * 提交当前环节的待办记录
     *  @param sqsxId 申请事项id
     *  @param jobId 当前环节id
     *  @param opinion 办理意见
     */
    public Result passJob(String sqsxId, String jobId, String opinion,String nextNodeName,String nextNodeDbrIds){
        //处理业务表的逻辑
        Result httpResult = this.passJob(flowConstant, sqsxId, jobId, opinion, nextNodeName, nextNodeDbrIds);
        return httpResult;
    }

    /**
     *
     * @param job
     * @param currentUser
     */
    private Result doJob(SpcySqsxJob job, CurrentUserVo currentUser, String opinion){
        String blrId = "";
        String blr = "";
        if (currentUser != null) {
            blrId = currentUser.getId();
            blr = currentUser.getName();
        }
        if (job == null){
            return Result.error("当前流程任务不存在，请重试");
        }
        if(SpcyConstant.BLZT_YB.equals(job.getFblzt())){
            return Result.error("当前任务已提交");
        }
        if(StringUtils.isBlank(job.getFdbrid())){
            return Result.error("当前任务未指定办理人");
        }
        if(!job.getFdbrid().contains(blrId)){
            return Result.error("当前登录用户无此任务的办理权限");
        }
        // 办理方式 竞争办理 、多人线性办理 、多人并行办理
        String blfs = job.getFblfs();
        if(StringUtils.isBlank(blfs)||blfs.equals(SpcyConstant.BLFS_DRJJ)){
            job.setFblr(blr);
            job.setFblsj(new Date());
            job.setFblyj(opinion);
            job.setFblzt(SpcyConstant.BLZT_YB);
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }else if(blfs.equals(SpcyConstant.BLFS_DRXX)  || blfs.equals(SpcyConstant.BLFS_DRBX)){
            //先根据多个人线性和多人并行的逻辑获得下一办理人
            String nextBlrId ="";
            String nextBlr ="";
            if(blfs.equals(SpcyConstant.BLFS_DRXX)){
                String ydbrIds[] = job.getFydbrid().split(",");
                String ydbrs[] = job.getFydbr().split(",");
                for (int i=0;i<ydbrIds.length;i++){
                    String dbrId = ydbrIds[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(dbrId.equals(blrId)){
                        if(i+1<ydbrIds.length){
                            nextBlrId=ydbrIds[i+1];
                            nextBlr=ydbrs[i+1];
                            break;
                        }
                    }
                }
            }else{
                String dbrIds[] = job.getFdbrid().split(",");
                String dbrs[] = job.getFdbr().split(",");
                for (int i=0;i<dbrIds.length;i++){
                    String dbrId = dbrIds[i];
                    String dbr = dbrs[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(!dbrId.equals(blrId)){
                        nextBlrId=nextBlrId+(StringUtils.isBlank(nextBlrId)?"":",")+dbrId;
                        nextBlr=nextBlr+(StringUtils.isBlank(nextBlr)?"":",")+dbr;
                    }
                }
            }

            //如果存在下一办理人 就继续待办，多人办理意见用@@分隔，办理时间、办理人、意见 用|分隔
            job.setFblr(blr);
            job.setFblsj(new Date());
            String blyj=(job.getFblyj()==null?"":job.getFblyj())+(StringUtils.isBlank(job.getFblyj())?"":"@@")+ DateConversionUtils.DateToString(new Date()) +"|"+blr+"|"+ opinion;
            job.setFblyj(blyj);
            if(StringUtils.isBlank(nextBlrId)){
                job.setFblzt(SpcyConstant.BLZT_YB);
            }else{
                job.setFblzt(SpcyConstant.BLZT_DB);
                job.setFdbrid(nextBlrId);
                job.setFdbr(nextBlr);
            }
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }
        return Result.error("待办任务未指定办理方式");
    }

    /**
     *
     * @param sqsxId
     * @param currentJob
     * @param currentUser
     * @param nextNodeName
     * @param nextNodeDbrIds
     * @return
     */
    public Result createNextJob(String sqsxId,SpcySqsxJob currentJob, CurrentUserVo currentUser,String nextNodeName,String nextNodeDbrIds){
        if (currentJob != null) {
            nextNodeName = getNextNodeName(currentJob.getFhjmc(), nextNodeName);
        }else {
            if (StringUtils.isBlank(nextNodeName)){
                return Result.error("下环节不能为空");
            }
        }
        if(nextNodeName.equals(YlqxFlowConstant.HJMC_LCJS)){
            SpcySqsxJob job = new SpcySqsxJob();
            job.setFhjmc(nextNodeName);

            return Result.ok("操作成功");
        }
        Map map = this.getNodeDbr(sqsxId,nextNodeName,nextNodeDbrIds);
        nextNodeDbrIds = map.get("dbrId").toString();
        String nextNodeDbrs = map.get("dbr").toString();
        if(StringUtils.isBlank(nextNodeDbrIds)){
            return Result.error("获取不到下一环节待办人");
        }
        SpcySqsxJob job = new SpcySqsxJob();
        job.setId(GetUuIdUtils.NotReplaceUuId());
        if(currentJob != null){
            job.setFsyhjid(currentJob.getId());
        }
        job.setFpid(sqsxId);
        job.setFhjmc(nextNodeName);
        if (currentUser != null) {
            job.setFfsrid(currentUser.getId());
            job.setFfsrmc(currentUser.getName());
        }
        job.setFfssj(new Date());

        job.setFdbrid(nextNodeDbrIds);
        job.setFdbr(nextNodeDbrs);
        job.setFydbrid(nextNodeDbrIds);
        job.setFydbr(nextNodeDbrs);

        // job.setFblfs(YlqxFlowConstant.getBlfs(nextNodeName));
        job.setFblzt(SpcyConstant.BLZT_DB);
        spcySqsxJobService.save(job);
        return Result.ok(job);
    }

    /**
     *
     * @param currentNodeName 可为空(如果为空，nextNodeName不为空)
     * @param nextNodeName 可为空(如果为空，currentNodename不为空)
     * @return
     */
    private String getNextNodeName(String  currentNodeName,String nextNodeName){
        if (StringUtils.isNotBlank(nextNodeName)){
            return nextNodeName;
        }else{
            return flowConstant.getNextNodeName(currentNodeName);
        }
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String sqsxid,String nodeName, String dbrIds){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        if(StringUtils.isNotBlank(dbrIds)){
            dbr = getDbrsByIds(dbrIds);
            dbrId = dbrIds;
        }else{
            String ywflcode = "";
            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
            if (sqsx != null && StringUtils.isNotBlank(sqsx.getFywflcode())){
                ywflcode = sqsx.getFywflcode();
            }

            // 审核
            if (nodeName.equals(SpBzFlowConstant.HJMC_SH)){
                // 科室负责人
                Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(ywflcode));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }


            // 审批
            if (nodeName.equals(SpBzFlowConstant.HJMC_SP)) {
                // 分管领导
                Map kzMap = getKsFgldByDeptName(SpcyConstant.getYwclNameByCode(ywflcode));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String nodeName, String dbrIds){
        return this.getNodeDbr(null,nodeName,dbrIds);
    }

    // 根据待办人id，获取名称拼接起来
    private String getDbrsByIds(String dbrIds){
        //把待办人按id查出来  把名字拼起来
        String dbr = "";
        List<String> dbrIdsList = Arrays.asList(dbrIds.split(","));
        List<YcSysUser> sysUserList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dbrIdsList)){
            sysUserList = ycSysUserService.listByIds(dbrIdsList);
        }

        if (CollectionUtils.isNotEmpty(sysUserList)){
            for (YcSysUser user : sysUserList){
                dbr += user.getRealname() + ",";
            }
        }

        return dbr;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 经办人
    public Map getKsjbrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_JBR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取对应科室的 分管领导
    public Map getKsFgldByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        YcSysUser fgldUserBydept = sysUserFgldService.getFgldUserBydept(deptName);
        if (fgldUserBydept != null) {
            dbrId = fgldUserBydept.getId();
            dbr = fgldUserBydept.getRealname();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取主办人
    public Map getZbrBySqsxId(String sqsxId){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        SpcySqsxBasic basic = spcySqsxBaiscService.getById(sqsxId);
        if (basic != null && StringUtils.isNotBlank(basic.getFzbr())){
            List<String> userids = Arrays.asList(basic.getFzbr().split(",|，"));
            if (CollectionUtils.isNotEmpty(userids)) {
                for (String uid : userids) {
                    YcSysUser sysUser = ycSysUserService.getById(uid);
                    if (sysUser != null) {
                        if (StringUtils.isBlank(dbrId)) {
                            dbrId += sysUser.getId();
                            dbr += sysUser.getRealname();
                        } else {
                            dbrId += "," + sysUser.getId();
                            dbr += "," + sysUser.getRealname();
                        }
                    }
                }
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

}
